/**
 * Created by admin on 2016/2/18.
 */
var async = require('async');
var Q = require('q');
var rewards = require('./rewards')
var giveCoupons = require('../../hongbao/models/rewards');
var OrderM = require('../../diy/controllers/order.js');
var _ = require('underscore')
module.exports = {
    //1、获取首页信息
    getHomeInfo:function(openid,uid){
        var q = Q.defer();
        async.waterfall([
            //首先获取用户的信息
            function(callback){
                rewards.getUserFromAV(openid).then(function(data){
                    if(data){
                        callback(null, {code:0,user:data});
                    }else{
                        callback(null, {code:1,user:{},msg:'没有获取到用户信息或者该用户未关注'})
                    }
                }).catch(function(err){
                    callback({code:-1,user:err})
                });
            },
            function(user,callback){
                rewards.countHome().then(function(data){
                    callback(null, {code:0,count:data,user:user})
                }).catch(function(err){
                    callback({code:-1,count:0,user:user})
                })

            },
            //判断是否是第一次进入，发放三张随机卡片

            function(card,callback){
                if(card.user.code === 0){
                    rewards.showHomeCard(uid).then(function(data){
                        if(data.code === 1){
                            callback(null, {code:0,count:card.count,user:card.user,card:data.cardInfo,isFirst:true})
                        }else{
                            callback(null, {code:0,count:card.count,user:card.user,card:data.cardInfo,isFirst:false})
                        }

                    }).catch(function(err){
                        callback({code:-1,count:card.count,user:card.user.user,card:[]})
                    })
                }else{
                    callback(null, {code:1,msg:'没有获取到用户信息，无法加载元宵数据'})
                }
            }
        ],function(err,result){
            if(err){
                q.reject(err);
            }else{
                q.resolve(result);
            }
        });
        return q.promise;
    },
    //2、赠送/讨要卡片时获取卡片信息（根据rewardid）
    getCardInfo:function(reward_id){
        var q = Q.defer();
        rewards.getRewardPoolByReward(reward_id).then(function(data){
            q.resolve(data);
        }).catch(function(err){
            q.reject(err);
        })
        return q.promise;
    },
    //3、创建赠送、讨要卡片页面是调用（创建赠送、讨要记录，status=0）
    //赠送
    createCardFlow:function(table,args){
        var q = Q.defer();
        async.waterfall([
            function(cb){
                rewards.giveOrSeekCard(table,args).then(function(data){
                    cb(null, data);
                }).catch(function(err){
                    cb(err);
                });
            },
            function(card_info,cb){
                if(card_info.objectId){
                    var card = card_info.get();
                    cb(null,{code:0,card_id:card_info.objectId});//创建成功
                    /*rewards.updatePersonalCenter(card.ownuid,card.reward,args.number,args.reward_name).then(function(data){
                        if(data.data.get().id){
                            cb(null,{code:0,card_id:card_info.objectId});//创建成功
                        }else{
                            cb({code:-1});//创建失败
                        }
                    }).catch(function(err){
                        cb(err);
                    });*/
                }else{
                    cb({code:-1});//创建失败
                }
            }
        ],function(err,result){
            if(err){
                //创建失败
                q.reject(err);
            }else{
                q.resolve(result);
            }
        });
        return q.promise;
    },
    //讨要
    seekCardFlow:function(table,args){
        var q = Q.defer();
        rewards.giveOrSeekCard(table,args).then(function(data){
            var card_info = data.get();
            q.resolve({code:0,card_id:data.objectId});
        }).catch(function(err){
            q.resolve(err);
        });
        return q.promise;
    },
    //4领取卡片（更新赠送、讨要表的uid，更新个人表的number）
    //警告：个人表的number在分享的时候就已经更新过了。
//赠送随机的三张卡片
    get3CardRandom:function(uid){
        var q = Q.defer();
        //从pool表中读取数据
        async.waterfall([
            function(cb){
                rewards.countPersonalCenter(uid).then(function(data){
                    if(data > 0){
                        cb({code:-4});
                    }else{
                        cb(null);
                    }
                }).catch(function(err){
                    cb({code:-4})
                });
            },
            //获取奖池数据
            function(cb){
                rewards.getCardFromPool1().then(function(data){
                    cb(null, {code:0,rewardPool:data._d})
                }).catch(function(err){
                    cb({code:9999,msg:'网络异常'});
                });
            },
            //生成随机数
            function(reward_pool,cb){
                //生成3个随机数
                var card = [] ;
                if(reward_pool.code === 0){
                    for(var i = 0;i<3;i++){
                        var id = Math.floor(Math.random()*10%(reward_pool.rewardPool.length));
                        card.push(reward_pool.rewardPool[id]);
                    }
                    cb(null, card);
                }else{
                    cb({code:9999,msg:'网络异常'});
                }
            },
            //2、添加奖品流水记录
            function(reward,cb){
                var flow1 = {uid:uid,type:reward[0].type,reward:reward[0].objectId,status:1}
                var flow2 = {uid:uid,type:reward[1].type,reward:reward[1].objectId,status:1}
                var flow3 = {uid:uid,type:reward[2].type,reward:reward[2].objectId,status:1}
                rewards.give3Rewards("lantern_reward_flow",flow1,flow2,flow3).then(function(){
                    cb(null, {code:0,reward:reward});
                }).catch(function(err){
                    cb(null,{code:-1,msg:'保存流水失败'});
                });
            },
            //3、向center表中创建或者更新一条记录
            function(reward,cb){
                //不论插入流水是否正常，都要更新个人中心表
                async.eachSeries(reward.reward,function(each,cb1){
                    rewards.updatePersonalCenter(uid,each.objectId,1,each.reward).then(function(data){
                        cb1(null, {code:0});
                    }).catch(function(err){
                        cb1(null, {code:-1});
                    });
                },function(){
                    cb(null, {code:0});
                });
            },
            //4、最后需要跟新home表，首先判断是否集齐6种的元宵，如果是，则创建一条，否则跳过
            function(res,cb){
                if(res.code === 0){
                    //更新成功，返回新的数组
                    rewards.countPersonalCenter(uid).then(function(data){
                        cb(null, {code:0,count:data})
                    }).catch(function(err){
                        cb(null, {code:0,count:0})
                    });
                }else{
                    cb(null, res)
                }
            },
            function(centerCount,cb){
                if(centerCount.code === 0){
                    if(centerCount.count >= 6){
                        rewards.updateHomeTable(uid,'add').then(function(data){
                            cb(null, {code:0});
                        }).catch(function(err){
                            cb(null, {code:-1})
                        });
                    }else{
                        cb(null, centerCount);
                    }
                }else{
                    cb(null, centerCount);
                }
            },
            function(req,cb){
                rewards.countHome().then(function(data){
                    cb(null, {code:0,count:data})
                }).catch(function(err){
                    cb({code:-1,count:0})
                })
            },
            function(req,cb){
                if(req.code === 0){
                    rewards.showHomeCard(uid).then(function(data){
                        if(data.code === 1){
                            cb(null, {code:0,count:req.count,card:data.cardInfo})
                        }else{
                            cb(null, {code:0,count:req.count,card:data.cardInfo})
                        }
                    }).catch(function(err){
                        cb({code:-1,count:card.count,card:[]})
                    })
                }else{
                    cb(null, {code:1,msg:'没有获取到用户信息，无法加载元宵数据'})
                }
            }
        ],function(err,result){
            if(err){
                q.reject(err);
            }else{
                q.resolve(result);
            }
        });
        //生成随机数，发放奖品

        //重新获取当前人卡片的数量

        return q.promise;
    },
    getCardFromFriend:function(table,id,uid){ //id为记录的id
        var q = Q.defer();
        async.waterfall([
            function(cb){
                rewards.countPersonalCenter(uid).then(function(data){
                    if(data > 0){
                        cb(null, {code:-4});
                    }else{
                        cb(null, {code:0});
                    }
                }).catch(function(err){
                    cb(null, {code:-4});
                });
            },
            //获取奖池数据
            function(res,cb){
                if(res.code === 0){
                    rewards.getCardFromPool1().then(function(data){
                        cb(null, {code:0,rewardPool:data._d})
                    }).catch(function(err){
                        cb(null, {code:-4});
                    });
                }else{
                    cb(null, {code:-4});
                }
            },
            //生成随机数
            function(reward_pool,cb){
                //生成3个随机数

                var card = [] ;
                if(reward_pool.code === 0){
                    for(var i = 0;i<3;i++){
                        var id = Math.floor(Math.random()*10%(reward_pool.rewardPool.length));
                        card.push(reward_pool.rewardPool[id]);
                    }
                    cb(null,{code:0,card:card});
                }else{
                    cb(null, {code:-4});
                }
            },
            //2、添加奖品流水记录
            function(res,cb){
                if(res.code === 0){
                    var reward = res.card ;
                    var flow1 = {uid:uid,type:reward[0].type,reward:reward[0].objectId,status:1}
                    var flow2 = {uid:uid,type:reward[1].type,reward:reward[1].objectId,status:1}
                    var flow3 = {uid:uid,type:reward[2].type,reward:reward[2].objectId,status:1}
                    rewards.give3Rewards("lantern_reward_flow",flow1,flow2,flow3).then(function(){
                        cb(null, {code:0,reward:reward});
                    }).catch(function(err){
                        cb(null,{code:-1,msg:'保存流水失败'});
                    });
                }else{
                    cb(null, {code:-4});
                }

            },
            //3、向center表中创建或者更新一条记录
             function(reward,cb){
                if(reward.code === 0){
                    //不论插入流水是否正常，都要更新个人中心表
                    async.eachSeries(reward.reward,function(each,cb1){
                        rewards.updatePersonalCenter(uid,each.objectId,1,each.reward).then(function(data){
                            cb1(null,data);
                        }).catch(function(err){
                            cb1(null);
                        });
                    },function(err){
                        cb(null);
                    });
                }else{
                    cb(null);
                }

            },
            function(callback){
                rewards.updateById(table,id,{uid:uid}).then(function(data){
                    callback(null, data.get());
                }).catch(function(err){
                    callback(err);
                });
            },
            //跟新个人数据
            function(cardInfo,callback){
                var reward = cardInfo.reward ;
                var reward_name = cardInfo.reward_name ;
                var number = 1 ;
                rewards.clearRewardInPersonal(uid,reward,number,reward_name).then(function(data){
                    console.log(data);
                    callback(null, {code:0,card:cardInfo,person:data});
                }).catch(function(err){
                    callback(err)
                });
            },
            ////跟新个人数据 减少赠送人信息的表不需要
            //function(cardInfo,callback){
            //    cardInfo = cardInfo.card;
            //    var reward = cardInfo.reward ;
            //    var number = -1 ;
            //    rewards.clearRewardInPersonal(cardInfo.ownuid,reward,number).then(function(data){
            //        console.log(data);
            //        callback(null, {code:0,card:cardInfo,person:data});
            //    }).catch(function(err){
            //        console.log(err);
            //        callback(err)
            //    });
            //}
        ],function(err,result){
            console.log(err);
            if(err){
                q.reject(err);
            }else{
                q.resolve(result);
            }
        })
        return q.promise;
    },
    //5、分享链接后的回调（扣减或增加相应的卡片数量）
    shareCallback:function(table,id,uid,imgUrl,nickname){
        var q = Q.defer();
        async.auto({
            getCardInfo:function(cb)
            {
                rewards.updateById(table, id, {status: 1,imgUrl:imgUrl,nickname:nickname}).then(function (data) {
                    cb(null, data);
                }).catch(function (err) {
                    cb(err);
                });
            }
            ,
            updatePersonal:["getCardInfo",function (cb,results) {
                var data = results.getCardInfo.get()
                rewards.updatePersonalCenter(uid, data.reward, -1, data.reward_name).then(function(res){
                    cb(null, data);
                }).catch(function (err) {
                    cb(err);
                });
            }] ,
            getCountPersonal:["updatePersonal",function (cb,results) {
                rewards.countPersonalCenter(uid).then(function(res){
                    cb(null, res);
                }).catch(function (err) {
                    cb(err);
                });
            }],
            updateHome:['getCountPersonal',function(cb,results){
                if(results.getCountPersonal >=6){
                    //想home表中插入或者不插入
                    rewards.updateHomeTable(uid,'add').then(function(res){
                        cb(null, res);
                    }).catch(function (err) {
                        cb(err);
                    });
                }else{
                    //想home表中更新或者不插入
                    rewards.updateHomeTable(uid,'').then(function(res){
                        cb(null, res);
                    }).catch(function (err) {
                        cb(err);
                    });
                }
            }],
            final:['updateHome',function(cb,results){
                cb(null, {code:0})
            }]
        },function(err,results){
            if(err){
                q.reject(err);
            }else{
                q.resolve(err);
            }
        });

        return q.promise;
    },
    yaoShareCallback:function(table,id,uid,imgUrl,nickname){
        var q = Q.defer();
        async.auto({
            getCardInfo:function(cb)
            {
                rewards.updateById(table, id, {status: 1,imgUrl:imgUrl,nickname:nickname}).then(function (data) {
                    cb(null, data);
                }).catch(function (err) {
                    cb(err);
                });
            }
        },function(err,results){
            if(err){
                q.reject(err);
            }else{
                q.resolve(err);
            }
        });

        return q.promise;
    },
    //6、捞元宵游戏
    /**
     * 捞元宵游戏说明
     * 【
     *  1、从奖池中获取记录（根据startTime和endTime）poolInfo = [{},{},{}]
     *  2、根据生成的随机数获取奖品数据 rewardInfo
     *  3、if(rewardInfo.type === 1) 免费时段，发放奖品，不扣减积分，else｛扣减20积分，发放奖品，添加积分流水｝
     *
     * 】
     * @param uid
     * @returns {*}
     */
    laoLanter:function(uid){
        var q = Q.defer();
        async.waterfall([
           //获取奖池数据
            function(cb){
                rewards.getRewardPool().then(function(data){
                    console.log(data);
                    cb(null, {code:0,rewardPool:data._d})
                }).catch(function(err){
                    cb({code:9999,msg:'网络异常'});
                });
            },
            //生成随机数
            function(reward_pool,cb){
                console.log(reward_pool);
                if(reward_pool.code === 0){
                    var id = _.random(0,reward_pool.rewardPool.length-1)
                    //var id = Math.floor(Math.random()*10%(reward_pool.rewardPool.length));
                    cb(null, reward_pool.rewardPool[id]);
                }else{
                    cb({code:9999,msg:'网络异常'});
                }
            },
            function(reward,cb){
                rewards.getRewardPool1().then(function(data){
                    cb(null,data._d,reward)
                }).catch(function(err){
                    cb({code:9999,msg:'网络异常'});
                });
            },
            //发放奖品  start
            //1、判断是否需要扣减积分
            function(new_re,reward,cb){
                if(new_re.type === 2){
                    rewards.updateUserFromAV(uid).then(function(data){
                        cb(null, reward);
                    }).catch(function(err){
                        cb(err);
                    });
                }else{
                    cb(null, reward);
                }
            },
            //奖池中的奖品数量减1
            function(reward,cb){
                console.log('=========')
                console.log(reward);
                var reward_id = reward.id ;
                rewards.updatePool(reward_id).then(function(){
                    cb(null, reward);
                }).catch(function(err){
                    cb({code:0,count:0,result:{code:reward.objectId,reward:reward.reward}});
                });
            },
            //2、添加奖品流水记录
            function(reward,cb){
                var reward_flow = {uid:uid,type:reward.type,reward:reward.objectId,status:1}
                console.log(reward_flow)
                rewards.insertRewardFlow(reward_flow).then(function(){
                    cb(null, {code:0,reward:reward});
                }).catch(function(err){
                    cb(err);
                });
            },

            //3、向center表中创建或者更新一条记录
            function(res,cb){
                var reward = res.reward ;
                //不论插入流水是否正常，都要更新个人中心表
                if([1,2,3,4,5,6].indexOf(reward.objectId) >=0){
                    rewards.updatePersonalCenter(uid,reward.objectId,1,reward.reward).then(function(data){
                        cb(null, {code:reward.objectId,reward:reward.reward});
                    }).catch(function(err){
                        cb(null, {code:-1});
                    });
                }else if(reward.objectId === 7){ // 优惠券
                    //执行发放优惠券和记录流水方法
                    giveCoupons.giveCoupons(uid,159,3).then(function(data){
                        if(data.code === 0){
                            //发放成功
                            cb(null, {code:reward.objectId,reward:reward.reward});
                        }else{
                            cb(null, {code:10,reward:reward.reward});//发放失败，直接跳过
                        }
                    }).catch(function(err){
                        cb(null, {code:reward.objectId,reward:reward.reward});//发放失败，直接跳过
                    });
                }else if(reward.objectId === 8){ //自提果汁
                    //调用自提订单接口
                    OrderM.diyaddOrder(uid,588).then(function(){
                        cb(null, {code:reward.objectId,reward:reward.reward});
                    }).catch(function(err){
                        console.log(err);
                        cb(null, {code:reward.objectId,reward:reward.reward});
                    });
                }else if(reward.objectId === 9){ //谢谢惠顾
                    //谢谢惠顾
                    cb(null, {code:reward.objectId,reward:reward.reward});
                }else{  //显示提示
                    cb(null, {code:10,reward:reward.reward});
                }
            },
            //4、最后需要跟新home表，首先判断是否集齐6种的元宵，如果是，则创建一条，否则跳过
            function(res,cb){
                if(res.code <= 6){
                    //更新成功，返回新的数组
                    rewards.countPersonalCenter(uid).then(function(data){
                        cb(null, {code:0,count:data,result:res})
                    }).catch(function(err){
                        cb(null, {code:0,count:0,result:res})
                    });
                }else{
                    cb(null, {code:0,count:0,result:res})
                }
            },
            function(centerCount,cb){
                console.log(centerCount);
                if(centerCount.code === 0){
                    if(centerCount.count >= 6){
                        rewards.updateHomeTable(uid,'add').then(function(data){
                            cb(null, {code:0,result:centerCount.result});
                        }).catch(function(err){
                            cb(null, {code:-1,result:centerCount.result})
                        });
                    }else{
                        cb(null, {code:0,result:centerCount.result});
                    }
                }else{
                    cb(null, {code:0,result:centerCount.result});
                }
            },
            function(req,cb){
                rewards.countHome().then(function(data){
                    cb(null, {code:0,count:data,result:req.result})
                }).catch(function(err){
                    cb({code:-1,count:0,result:req.result})
                })
            },
            function(req,cb){
                if(req.code === 0){
                    rewards.showHomeCard(uid).then(function(data){
                        if(data.code === 1){
                            cb(null, {code:0,count:req.count,card:data.cardInfo,result:req.result})
                        }else{
                            cb(null, {code:0,count:req.count,card:data.cardInfo,result:req.result})
                        }
                    }).catch(function(err){
                        cb({code:-1,count:req.count,card:[],result:req.result})
                    })
                }else{
                    cb({code:-1,msg:'没有获取到用户信息，无法加载元宵数据'})
                }
            }
        ],function(err,result){
            if(err){
                q.reject(err);
            }else{
                q.resolve(result);
            }
        });
        return q.promise;
    },
    getCurrentReward:function(){
        var q = Q.defer();
        async.waterfall([
            function(cb){
                rewards.getRewardPool1().then(function(data){
                    console.log(data._d);
                    cb(null, {code:0,rewardPool:data._d})
                }).catch(function(err){
                    cb({code:9999,msg:'网络异常'});
                });
            },
            /*//生成随机数
            function(reward_pool,cb){
                if(reward_pool.code === 0){
                    var id = _.random(0,5)
                    //var id = Math.floor(Math.random()*10%(reward_pool.rewardPool.length));
                    cb(null, {code:0,rewardPool:reward_pool.rewardPool[id]});
                }else{
                    cb({code:9999,msg:'网络异常'});
                }
            }*/
        ],function(err,result){
            if(err){
                q.reject(err);
            }else{
                q.resolve(result)
            }
        });
        return q.promise;
    },
    //7、发放终极大奖

    //打开好友讨要链接时调用
    openSeekPage:function(uid,card_id){
        //根据card_id展示页面，根据uid和reward找到我是否有这张卡片
        var q = Q.defer();
        async.waterfall([
            function(cb){
                rewards.getInfoById('lantern_seek_reward',card_id).then(function(data){
                    cb(null, data);
                }).catch(function(err){
                    cb(err)
                })
            },
            function(card_info,cb){
                console.log(card_info.get().id)
                if(card_info.get().id){
                    rewards.getCenterInfo(uid, card_info.get().reward).then(function(data){
                        if(data.get('id')){
                            cb(null, {code:0,card:card_info.get(),number:data.get('number')});
                        }else{
                            cb(null, {code:0,card:card_info.get(),number:0});
                        }
                    }).catch(function(err){
                        cb(err)
                    })
                }else{
                    cb(null, {code:0,card:card_info.get(),number:0});
                }
            }
        ],function(err,result){
            if(err){
                q.reject(err);
            }else{
                q.resolve(result);
            }
        })
        return q.promise;
    },
    //给好友发放卡片
    giveCardToFriend:function(args){
        //更新lantern_seek_reward ,更新lantern_personal_center
        var q = Q.defer();
        async.waterfall([
            function(cb){
                var uid = args.uid,
                    reward = args.reward,
                    number = -1,
                    reward_name = args.reward_name ;
                rewards.updatePersonalCenter(uid,reward,number,reward_name).then(function(data){
                    console.log('======1=========');
                    console.log(data);
                    cb(null, {code:0});
                }).catch(function(err){
                    cb(err)
                });
            },
            function(info,cb){
                rewards.insertSeek(args).then(function(data){
                    console.log('======2=========');
                    console.log(data);
                    cb(null,  {code:0});
                }).catch(function(err){
                    cb(err)
                });
            },
            function(res,cb){
                var uid = args.ownuid,
                    reward = args.reward,
                    number = 1,
                    reward_name = args.reward_name ;
                rewards.updatePersonalCenter(uid,reward,number,reward_name).then(function(data){
                    console.log('======3=========');
                    console.log(data);
                    cb(null,  {code:0});
                }).catch(function(err){
                    cb(err)
                });
            }
        ],function(err,result){
            if(err){
                q.reject(err);
            }else{
                q.resolve(result);
            }
        });
        return q.promise;
    },
    //根据card_id到lantern_give_reward表中查找记录，并显示
    openGivePage:function(card_id){
        var q = Q.defer();
        rewards.getInfoById('lantern_give_reward',card_id).then(function(data){
            q.resolve(data.get());
        }).catch(function(err){
            q.reject(err)
        })
        return q.promise;
    },

    getCountRealFrom:function(){

    }

    ,

    /**
     * 发放最终10万现金（只能手动领取）
     * @param uid
     * @returns {*}
     */
    giveFinalReward:function(uid){
        var q = Q.defer();
        async.waterfall([
            //首先判断是否符合条件，cnt>6
            function(cb){

            },
            //判断w_flag或者l_flag 是否为true，如果为true，表示已领取过，否则未领取，可以继续领取
            function(cb){

            },
            //发放奖品
            function(){

            }
        ],function(err,result){
            if(err){
                q.reject(err)
            }else{
                q.resolve(result);
            }
        });
        return q.promise;
    },
    get_zsm_info:function(uid){
        var q = Q.defer();
        rewards.getZSMInfo(uid).then(function(data){
            if(data.code === 0){
                q.resolve({code:0,zsmInfo:data.info});
            }else{
                q.reject({code:-1,msg:'您未达到领奖条件'});
            }
        }).catch(function(err){
            q.reject({code:-1,msg:'您未达到领奖条件'});
        });
        return q.promise;

    },
    /**
     * 领取自提苹果,首先判断是否符合领取5个品种的元宵，并且状态是未领取过的
     * @param uid
     * @returns {*}
     */
    give_apple:function(uid){
        var q = Q.defer();
        async.auto({
            getZSMInfo:function(cb){
                rewards.getZSMInfo(uid).then(function(data){
                    if(data.code === 0){
                        cb(null, {code:0,zsmInfo:data.info});
                    }else{
                        cb({code:-1,msg:'您未达到领奖条件'});
                    }
                }).catch(function(err){
                    cb({code:-1,msg:'您未达到领奖条件'});
                });
            },
            //判断是否有符合条件的奖品 w_flag =?= null
            canGiveReward:['getZSMInfo',function(cb,results){

                if(results.getZSMInfo.code === 0){
                    var zsmInfo = results.getZSMInfo.zsmInfo ;
                    if( zsmInfo.cnt === 5 ){
                        if(!zsmInfo.w_flag){
                            cb(null, {code:0,msg:'符合领取条件'})
                        }else{
                            cb({code:-2,msg:'已领取过'})
                        }
                    }else{
                        cb({code:-1,msg:'不符合领取条件'})
                    }
                }else{
                    cb({code:-1,msg:'不符合领取条件'})
                }
            }],
            updateZSMInfo:['canGiveReward',function(cb,results){
                if(results.canGiveReward.code === 0){
                    var args = {w_flag:1,w_time:new Date().getTime()};
                    //发放奖品
                    rewards.updateZSMInfo(uid,args).then(function(data){
                        cb(null, {code:0,msg:'领取成功'})
                    }).catch(function(err){
                        cb({code:-3,msg:'领取失败，更新zsm表时错误'});
                    });
                }else{
                    cb({code:-1,msg:'不符合领取条件'})
                }
            }],
            giveApple:['updateZSMInfo',function(cb,results){
                if(results.updateZSMInfo.code === 0){
                    //发放水果，调用自提订单接口
                    OrderM.diyaddOrder(uid,881).then(function(){
                        cb(null, {code:0,msg:'领取成功'});
                    }).catch(function(err){
                        cb({code:-3,msg:'领取失败'});
                    });
                }else{
                    cb({code:-3,msg:'领取失败'});
                }
            }]
        },function(err,results){
            if(err){
                q.reject(err);
            }else{
                q.resolve(results.giveApple);
            }
        });

        return q.promise;
    },
    give_amount:function(uid){
        var q = Q.defer();
        async.auto({
            getZSMInfo:function(cb){
                rewards.getZSMInfo(uid).then(function(data){
                    if(data.code === 0){
                        cb(null, {code:0,zsmInfo:data.info});
                    }else{
                        cb({code:-1,msg:'您未达到领奖条件'});
                    }
                }).catch(function(err){
                    cb({code:-1,msg:'您未达到领奖条件'});
                });
            },
            //判断是否有符合条件的奖品 w_flag =?= null
            canGiveReward:['getZSMInfo',function(cb,results){
                if(results.getZSMInfo.code === 0){
                    var zsmInfo = results.getZSMInfo.zsmInfo ;
                    console.log(!zsmInfo.l_flag);
                    if( zsmInfo.cnt === 6 ){
                        if(!zsmInfo.l_flag){
                            cb(null, {code:0,msg:'符合领取条件'})
                        }else{
                            cb({code:-2,msg:'已领取过'})
                        }
                    }else{
                        cb({code:-1,msg:'不符合领取条件'})
                    }
                    /*if(!zsmInfo.l_flag && zsmInfo.cnt === 6){
                        cb(null, {code:0,msg:'符合领取苹果条件'})
                    }else{
                        cb({code:-1,msg:'不符合领取苹果条件'})
                    }*/
                }else{
                    cb({code:-1,msg:'不符合领取苹果条件'})
                }
            }],
            updateZSMInfo:['canGiveReward',function(cb,results){
                if(results.canGiveReward.code === 0){
                    var args = {l_flag:1,l_time:new Date().getTime()};
                    //发放奖品
                    rewards.updateZSMInfo(uid,args).then(function(data){
                        cb(null, {code:0,msg:'领取成功'})
                    }).catch(function(err){
                        console.log(err);
                        cb({code:-2,msg:'领取失败，更新zsm表时错误',err:err});
                    });
                }else{
                    cb({code:-1,msg:'不符合领取苹果条件'})
                }
            }],
            giveAmount:['updateZSMInfo',function(cb,results){
                if(results.updateZSMInfo.code === 0){
                    //发放余额，记录余额流水
                    rewards.giveCash(uid,9.66).then(function(data){
                        if(data.code === 0){
                            cb(null, {code:0,msg:'领取成功'});
                        }else{
                            cb({code:-3,msg:'领取失败'});
                        }
                    }).catch(function(err){
                        cb({code:-3,msg:'发放失败了'})
                    });
                }else{
                    cb({code:-3,msg:'领取失败'});
                }
            }]
        },function(err,results){
            if(err){
                q.reject(err);
            }else{
                q.resolve(results.giveAmount);
            }
        });

        return q.promise;
    },
    //发放优惠券
    give_coupon:function(uid){
        var q = Q.defer();
        async.auto({
            getZSMInfo:function(cb){
                rewards.getZSMInfo(uid).then(function(data){
                    if(data.code === 0){
                        cb(null, {code:0,zsmInfo:data.info});
                    }else{
                        cb({code:-1,msg:'您未达到领奖条件'});
                    }
                }).catch(function(err){
                    cb({code:-1,msg:'您未达到领奖条件'});
                });
            },
            //判断是否有符合条件的奖品 w_flag =?= null
            canGiveReward:['getZSMInfo',function(cb,results){

                if(results.getZSMInfo.code === 0){
                    var zsmInfo = results.getZSMInfo.zsmInfo ;

                    if( zsmInfo.size >= 50 ){
                        if(!zsmInfo.y_flag){
                            cb(null, {code:0,msg:'符合领取条件'})
                        }else{
                            cb({code:-2,msg:'已领取过'})
                        }
                    }else{
                        cb({code:-1,msg:'不符合领取条件'})
                    }
                    /*if(!zsmInfo.y_flag && zsmInfo.size >= 50){
                        cb(null, {code:0,msg:'符合领取苹果条件'})
                    }else{
                        cb({code:-1,msg:'不符合领取苹果条件'})
                    }*/
                }else{
                    cb({code:-1,msg:'不符合领取苹果条件'})
                }
            }],
            updateZSMInfo:['canGiveReward',function(cb,results){
                if(results.canGiveReward.code === 0){
                    var args = {y_flag:1,y_time:new Date().getTime()};
                    //发放奖品
                    rewards.updateZSMInfo(uid,args).then(function(data){
                        cb(null, {code:0,msg:'领取成功'})
                    }).catch(function(err){
                        cb({code:-2,msg:'领取失败，更新zsm表时错误'});
                    });
                }else{
                    cb({code:-1,msg:'不符合领取苹果条件'})
                }
            }],
            giveCoupon:['updateZSMInfo',function(cb,results){
                if(results.updateZSMInfo.code === 0){
                    //发放水果，调用自提订单接口
                    giveCoupons.giveCoupons(uid,165,3).then(function(data){
                        if(data.code === 0){
                            //发放成功
                            cb(null, {code:0,mgs:'发放成功'});
                        }else{
                            cb({code:-2,msg:'领取失败'});//发放失败，直接跳过
                        }
                    }).catch(function(err){
                        cb({code:-2,msg:'领取失败'});//发放失败，直接跳过
                    });
                }else{
                    cb({code:-2,msg:'领取失败'});
                }
            }]
        },function(err,results){
            if(err){
                q.reject(err);
            }else{
                q.resolve(results.giveCoupon);
            }
        });

        return q.promise;
    }

};